package com.shizhanzhe.zxbapp.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.CustomObject;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.SharedPreferencesUtils;
import com.shizhanzhe.zxbapp.utils.Util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import xcs.ert.jlj.os.df.AdExtraTaskStatus;
import xcs.ert.jlj.os.df.AppExtraTaskObject;
import xcs.ert.jlj.os.df.AppExtraTaskObjectList;
import xcs.ert.jlj.os.df.AppSummaryObject;

/**
 * Created by zz9527 on 2018/10/12.
 */
public class GVAdapter extends BaseAdapter {
    private final LayoutInflater inflater;
    private Context mContext;
    private List<CustomObject> mCustomObjectList;
    private int type;

    public GVAdapter(List<CustomObject> mCustomObjectList, Context context, int type) {
        UserBean.divide = (String) SharedPreferencesUtils.getParam(context, "divide", "");
        UserBean.vipdivide = (String) SharedPreferencesUtils.getParam(context, "vipdivide", "");
        UserBean.uid = (int) SharedPreferencesUtils.getParam(context, "uid", 0);
        this.mCustomObjectList = mCustomObjectList;
        this.mContext = context;
        this.type = type;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mCustomObjectList.size();
    }

    @Override
    public Object getItem(int i) {
        return mCustomObjectList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }
    @SuppressLint("CheckResult")
    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        if (type == 1) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_gv, null);
                holder = new ViewHolder();
                holder.app_icon = (ImageView) convertView.findViewById(R.id.gv_iv);
//                holder.mohu = (ImageView) convertView.findViewById(R.id.mohu);
                holder.app_name = convertView.findViewById(R.id.gv_title);
                holder.app_points = convertView.findViewById(R.id.gv_price);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final CustomObject item = mCustomObjectList.get(i);
            final AppSummaryObject appSummaryObject = item.getAppSummaryObject();
            // 设置广告图标
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.transform(new RoundedCorners(15)).error(R.mipmap.logo);
            if (item.getAppicon() == null) {
                holder.app_icon.setVisibility(View.INVISIBLE);
            } else {
                if (item.getAppicon().contains("http")) {
                    Glide.with(mContext).load(item.getAppicon()).apply(requestOptions).into(holder.app_icon);
                }else {
                    Glide.with(mContext).load(Path.img(item.getAppicon())).apply(requestOptions).into(holder.app_icon);
                }
                holder.app_icon.setVisibility(View.VISIBLE);
            }
            // 设置广告名字
            if (appSummaryObject.getAppName().contains("#")) {
                holder.app_name.setText(appSummaryObject.getAppName().split("#")[0]);
//                blurBitmap(((BitmapDrawable)holder.mohu.getDrawable()).getBitmap());
                holder.app_points.setText(appSummaryObject.getAppName().split("#")[3] + "元");
            } else {
                if (appSummaryObject.getAppName().contains("-需注册")) {
                    holder.app_name.setText(appSummaryObject.getAppName().split("-")[0]);
                } else {
                    holder.app_name.setText(appSummaryObject.getAppName());
                }
                holder.app_points.setText(Util.Sub((double) getTotalPoints(appSummaryObject) * Double.parseDouble(UserBean.divide) / 100 + "") + "元");
            }
            // 设置广告积分
        } else if (type == 2) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_gv_task, null);
                holder = new ViewHolder();
                holder.app_icon = convertView.findViewById(R.id.gv_iv);
                holder.app_name = convertView.findViewById(R.id.gv_title);
                holder.ivvip = convertView.findViewById(R.id.iv_vip);
                holder.app_points = convertView.findViewById(R.id.gv_price);
                holder.vipdivide = convertView.findViewById(R.id.vipdivide);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            CustomObject item = mCustomObjectList.get(i);
            final AppSummaryObject appSummaryObject = item.getAppSummaryObject();
            // 设置广告图标
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.transform(new RoundedCorners(15)).error(R.mipmap.logo);
            if (item.getAppicon() == null) {
                holder.app_icon.setVisibility(View.INVISIBLE);
            } else {
                if (item.getAppicon().contains("http")) {
                    Glide.with(mContext).load(item.getAppicon()).apply(requestOptions).into(holder.app_icon);
                }else {
                    Glide.with(mContext).load(Path.img(item.getAppicon())).apply(requestOptions).into(holder.app_icon);
                }
                holder.app_icon.setVisibility(View.VISIBLE);
            }
            // 设置广告名字
            if (appSummaryObject.getAppName().contains("#")) {
                holder.ivvip.setVisibility(View.INVISIBLE);
                holder.vipdivide.setVisibility(View.INVISIBLE);
                holder.app_name.setText(appSummaryObject.getAppName().split("#")[0]);
                holder.app_points.setText(appSummaryObject.getAppName().split("#")[3]  + "元");
                holder.vipdivide.setText(appSummaryObject.getAppName().split("#")[3]  + "元");
            } else {
                holder.ivvip.setVisibility(View.VISIBLE);
                holder.vipdivide.setVisibility(View.VISIBLE);
                if (appSummaryObject.getAppName().contains("-需注册")) {
                    holder.app_name.setText(appSummaryObject.getAppName().split("-")[0]);
                } else {
                    holder.app_name.setText(appSummaryObject.getAppName());
                }
                holder.app_points.setText(Util.Sub((double) getTotalPoints(appSummaryObject) * Double.parseDouble(UserBean.divide) / 100 + "") + "元");
                holder.vipdivide.setText(Util.Sub((double) getTotalPoints(appSummaryObject) * (Double.parseDouble(UserBean.divide) + Double.parseDouble(UserBean.vipdivide)) / 100 + "") + "元");
            }
            //设置广告积分
        }
        return convertView;

    }

    private static class ViewHolder {
        ImageView app_icon;
        ImageView ivvip;
        TextView app_name;
        TextView app_points;
        TextView vipdivide;
    }

    /**
     * 如果任务未完成就获取指定广告的所有积分（正常完成的积分+可完成的追加任务积分）
     */
    private int getTotalPoints(AppSummaryObject appSummaryObject) {
        int totalpoints = appSummaryObject.getPoints();
        AppExtraTaskObjectList tempList = appSummaryObject.getExtraTaskList();
        if (tempList != null && tempList.size() > 0) {
            for (int i = 0; i < tempList.size(); ++i) {
                AppExtraTaskObject extraTaskObject = tempList.get(i);
                if (extraTaskObject.getStatus() == AdExtraTaskStatus.NOT_START ||
                        extraTaskObject.getStatus() == AdExtraTaskStatus.IN_PROGRESS) {
                    totalpoints += extraTaskObject.getPoints();
                }
            }
        }
        return totalpoints;
    }

    //模糊效果
    public Bitmap blurBitmap(Bitmap bitmap) {
        Bitmap outBitmap = Bitmap.createBitmap(50,50, Bitmap.Config.ARGB_8888);
        RenderScript rs = RenderScript.create(mContext);
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
        Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
        blurScript.setRadius(25.f);
        blurScript.setInput(allIn);
        blurScript.forEach(allOut);
        allOut.copyTo(outBitmap);
        bitmap.recycle();
        rs.destroy();
        return outBitmap;
    }
    //下载网络图片
    public Bitmap getLocalOrNetBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(url).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            byte[] b = new byte[1024];
            int read;
            while ((read = in.read(b)) != -1) {
                out.write(b, 0, read);
            }
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}
